<template>
  <div class="repair-track">
    <van-nav-bar
      :title="$t('repair.track.title')"
      left-arrow
      @click-left="router.back()"
    />
    
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div v-if="loading" class="loading-container">
        <van-loading size="24px">{{ $t('repair.common.loading') }}</van-loading>
      </div>
      
      <div v-else-if="orderInfo" class="track-content">
        <!-- 工单头部 -->
        <div class="order-header">
          <div class="case-info">
            <div class="case-no">{{ orderInfo.caseNo }}</div>
            <div v-if="orderInfo.estimatedCompletionTime" class="estimated-time">
              <van-icon name="clock-o" />
              {{ $t('repair.track.estimatedTime') }}: {{ getEstimatedDays() }}{{ $t('repair.track.daysLater') }}
            </div>
          </div>
        </div>
        
        <!-- 当前状态卡片 -->
        <div class="status-card">
          <div class="status-icon">
            <van-icon :name="getStatusIcon()" :color="getStatusColor()" size="48" />
          </div>
          <div class="status-content">
            <div class="status-title">{{ $t(`repair.status.${orderInfo.status}`) }}</div>
            <div class="status-desc">{{ $t(`repair.statusDesc.${orderInfo.status}`) }}</div>
          </div>
        </div>
        
        <!-- 进度时间轴 -->
        <div class="progress-section">
          <div class="section-title">{{ $t('repair.track.progress') }}</div>
          <ProgressTimeline :progress-list="orderInfo.progress || []" />
        </div>
        
        <!-- 报价信息 (如果有) -->
        <div v-if="orderInfo.quote" class="quote-section">
          <div class="section-title">{{ $t('repair.quote.title') }}</div>
          <van-cell-group inset>
            <van-cell :title="$t('repair.quote.total')" :value="`¥${orderInfo.quote.totalAmount}`" />
            <van-cell :title="$t('repair.quote.validPeriod')" :value="`24${$t('repair.quote.hours')}`" />
          </van-cell-group>
          <div class="quote-actions">
            <van-button type="primary" block @click="confirmQuote">
              {{ $t('repair.quote.confirmRepair') }}
            </van-button>
            <van-button block @click="rejectQuote">
              {{ $t('repair.quote.rejectRepair') }}
            </van-button>
          </div>
        </div>
        
        <!-- 工单信息 -->
        <div class="info-section">
          <div class="section-title">{{ $t('repair.track.orderInfo') }}</div>
          <van-cell-group inset>
            <van-cell :title="$t('repair.track.deviceModel')" :value="orderInfo.deviceModel" />
            <van-cell :title="$t('repair.track.faultDesc')" :value="orderInfo.faultDescription" />
            <van-cell :title="$t('repair.track.serviceType')" :value="getServiceTypeText(orderInfo.serviceType)" />
            <van-cell v-if="orderInfo.serviceCenterName" :title="$t('repair.track.serviceCenter')" :value="orderInfo.serviceCenterName" />
            <van-cell :title="$t('repair.track.createTime')" :value="orderInfo.createTime" />
          </van-cell-group>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <van-button v-if="orderInfo.canUrge" icon="bell-o" @click="urgeOrder">
            {{ $t('repair.track.urge') }}
          </van-button>
          <van-button icon="service-o" @click="contactService">
            {{ $t('repair.track.contact') }}
          </van-button>
          <van-button v-if="orderInfo.canCancel" icon="cross" @click="cancelOrder">
            {{ $t('repair.track.cancelOrder') }}
          </van-button>
          <van-button v-if="orderInfo.status === 'SHIPPED'" type="primary" @click="confirmReceipt">
            {{ $t('repair.track.confirmReceipt') }}
          </van-button>
        </div>
      </div>
      
      <van-empty v-else :description="$t('repair.common.noData')" />
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { showToast, showSuccessToast, showDialog, showConfirmDialog } from 'vant'
import { 
  getRepairOrderByCase, 
  urgeRepairOrder, 
  cancelRepairOrder as cancelOrderApi,
  confirmReceipt as confirmReceiptApi,
  confirmQuote as confirmQuoteApi,
  rejectQuote as rejectQuoteApi
} from '@/api/repair'
import ProgressTimeline from './components/ProgressTimeline.vue'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()

const loading = ref(false)
const refreshing = ref(false)
const orderInfo = ref(null)

// 获取工单详情
const getOrderDetail = async () => {
  loading.value = true
  try {
    const res = await getRepairOrderByCase(route.params.caseNo)
    orderInfo.value = res.data
  } catch (error) {
    showToast('获取工单详情失败')
  } finally {
    loading.value = false
  }
}

// 下拉刷新
const onRefresh = async () => {
  await getOrderDetail()
  refreshing.value = false
}

// 获取状态图标
const getStatusIcon = () => {
  const iconMap = {
    'PENDING': 'clock-o',
    'ACCEPTED': 'checked',
    'DETECTING': 'search',
    'QUOTED': 'balance-o',
    'REPAIRING': 'setting-o',
    'QUALITY_CHECKED': 'passed',
    'SHIPPED': 'logistics',
    'COMPLETED': 'success',
    'CANCELLED': 'cross'
  }
  return iconMap[orderInfo.value?.status] || 'clock-o'
}

// 获取状态颜色
const getStatusColor = () => {
  const colorMap = {
    'PENDING': '#ff976a',
    'ACCEPTED': '#1989fa',
    'DETECTING': '#1989fa',
    'QUOTED': '#ff976a',
    'REPAIRING': '#1989fa',
    'QUALITY_CHECKED': '#07c160',
    'SHIPPED': '#07c160',
    'COMPLETED': '#07c160',
    'CANCELLED': '#969799'
  }
  return colorMap[orderInfo.value?.status] || '#969799'
}

// 获取预计完成天数
const getEstimatedDays = () => {
  if (!orderInfo.value?.estimatedCompletionTime) return 0
  const now = new Date()
  const estimated = new Date(orderInfo.value.estimatedCompletionTime)
  const days = Math.ceil((estimated - now) / (1000 * 60 * 60 * 24))
  return days > 0 ? days : 0
}

// 获取服务类型文本
const getServiceTypeText = (type) => {
  const typeMap = {
    'IN_STORE': t('repair.submit.serviceType.inStore'),
    'MAIL_IN': t('repair.submit.serviceType.mailIn'),
    'ON_SITE': t('repair.submit.serviceType.onSite')
  }
  return typeMap[type] || ''
}

// 催单
const urgeOrder = async () => {
  try {
    await urgeRepairOrder(orderInfo.value.id)
    showSuccessToast(t('repair.track.urgeSuccess'))
  } catch (error) {
    showToast(t('repair.track.urgeLimit'))
  }
}

// 联系客服
const contactService = () => {
  showDialog({
    title: t('repair.track.contact'),
    message: '客服电话: 010-1132546'
  })
}

// 取消工单
const cancelOrder = async () => {
  showConfirmDialog({
    title: t('repair.track.cancelOrder'),
    message: t('repair.track.cancelConfirm')
  }).then(async () => {
    try {
      await cancelOrderApi(orderInfo.value.id, { reason: '用户取消' })
      showSuccessToast(t('repair.track.cancelSuccess'))
      await getOrderDetail()
    } catch (error) {
      showToast('取消失败')
    }
  })
}

// 确认收货
const confirmReceipt = async () => {
  showConfirmDialog({
    title: t('repair.track.confirmReceipt'),
    message: t('repair.track.receiptConfirm')
  }).then(async () => {
    try {
      await confirmReceiptApi(orderInfo.value.id)
      showSuccessToast(t('repair.track.receiptSuccess'))
      await getOrderDetail()
    } catch (error) {
      showToast('确认失败')
    }
  })
}

// 确认报价
const confirmQuote = async () => {
  showConfirmDialog({
    title: t('repair.quote.confirmTitle'),
    message: t('repair.quote.confirmMessage')
  }).then(async () => {
    try {
      await confirmQuoteApi(orderInfo.value.id, {})
      showSuccessToast(t('repair.quote.confirmSuccess'))
      await getOrderDetail()
    } catch (error) {
      showToast('确认失败')
    }
  })
}

// 拒绝报价
const rejectQuote = async () => {
  showConfirmDialog({
    title: t('repair.quote.rejectTitle'),
    message: t('repair.quote.rejectMessage')
  }).then(async () => {
    try {
      await rejectQuoteApi(orderInfo.value.id, { reason: '价格不合适' })
      showSuccessToast(t('repair.quote.rejectSuccess'))
      await getOrderDetail()
    } catch (error) {
      showToast('操作失败')
    }
  })
}

onMounted(() => {
  getOrderDetail()
})
</script>

<style scoped lang="scss">
.repair-track {
  min-height: 100vh;
  background: linear-gradient(180deg, #f0f9ff 0%, #f7f8fa 100%);
  padding-bottom: 20px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100px 0;
}

.track-content {
  padding: 16px;
}

.order-header {
  background: #fff;
  border-radius: 12px;
  padding: 18px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.case-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.case-no {
  font-size: 17px;
  font-weight: 600;
  color: #323233;
  letter-spacing: 0.5px;
}

.estimated-time {
  font-size: 13px;
  color: #969799;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 12px;
  background: #f7f8fa;
  border-radius: 12px;
}

.status-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 28px 24px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  color: #fff;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
    animation: ripple 3s ease-out infinite;
  }
}

@keyframes ripple {
  0% {
    transform: scale(0.8);
    opacity: 1;
  }
  100% {
    transform: scale(1.2);
    opacity: 0;
  }
}

.status-icon {
  margin-right: 20px;
  position: relative;
  z-index: 1;
  animation: iconFloat 2s ease-in-out infinite;
}

@keyframes iconFloat {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

.status-content {
  flex: 1;
  position: relative;
  z-index: 1;
}

.status-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-desc {
  font-size: 14px;
  opacity: 0.95;
  line-height: 1.5;
}

.progress-section,
.quote-section,
.info-section {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 16px;
  position: relative;
  padding-left: 12px;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 2px;
  }
}

.quote-actions {
  display: flex;
  gap: 12px;
  margin-top: 16px;
  
  .van-button {
    flex: 1;
    height: 44px;
    border-radius: 22px;
    font-size: 15px;
    font-weight: 500;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.96);
    }
  }
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 0 16px;
  
  .van-button {
    flex: 1;
    min-width: calc(50% - 6px);
    height: 40px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.3s;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    
    &:active {
      transform: translateY(2px);
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    }
  }
}

// 优化 Vant 组件样式
:deep(.van-cell-group) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.van-cell) {
  padding: 14px 16px;
  
  .van-cell__title {
    font-weight: 500;
    color: #646566;
  }
  
  .van-cell__value {
    color: #323233;
    font-weight: 500;
  }
}
</style>

